import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    //博客列表页获取登录用户信息
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应格式
        req.setCharacterEncoding("utf8");
        //获取session会话
        HttpSession session = req.getSession();
        if(session == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录!");
            return;
        }
        //获取user对象
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录!");
            return;
        }
        user.setPassword("");//保护信息安全
        //获取blogId
        String blogId = req.getParameter("blogId");
        if(blogId == null) {
            //博客列表页——获取当前登录用户信息
            getUser(req, resp, user);
        } else {
            //博客详情页——获取当前博客作者信息
            getAuthor(req, resp, blogId);
        }

    }

    private void getAuthor(HttpServletRequest req, HttpServletResponse resp, String blogId) throws IOException {
        //从数据库中获取相应博客
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
        if(blog == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前博客ID不存在!");
            return;
        }
        //从对应博客中获取userId,并获取对应的user对象
        int userId = blog.getUserId();
        UserDao userDao = new UserDao();
        User user = userDao.selectById(userId);
        if(user == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("该作者不存在!");
            return;
        }
        user.setPassword("");//保护信息安全
        //处理响应
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }

    private void getUser(HttpServletRequest req, HttpServletResponse resp, User user) throws IOException {
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}
